﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;


namespace testcpi
{
    public class HttpClientHelper
    {
        private static readonly object LockObj = new object();
        private static HttpClient client = null;
        public HttpClientHelper()
        {
            GetInstance();
        }
        public static HttpClient GetInstance()
        {

            if (client == null)
            {
                lock (LockObj)
                {
                    if (client == null)
                    {
                        //requestconfig requestconfig = requestconfig.custom()
                        //.setSocketTimeout(10000)
                        //.setConnectTimeout(10000)
                        //.setConnectionRequestTimeout(10000)
                        //.build();
                        //配置httpClient
                        //var socketsHttpHandler = new SocketsHttpHandler()
                        //{
                        //    AllowAutoRedirect = true,// 默认为true,是否允许冲顶定向
                        //    MaxAutomaticRedirections = 50,//最多重定向几次,默认50次
                        //                                  //MaxConnectionsPerServer = 100,//连接池中统一TcpServer的最大连接数
                        //    UseCookies = false// 是否自动处理cookie
                        //};
                        client = new HttpClient();
                        client.Timeout = TimeSpan.FromSeconds(3);
                        client.DefaultRequestHeaders.Add("x-www-foo", "123");//测试用
                        //var httphamdle = new HttpClientHandler();
                        //client.Timeout
                        //client = new HttpClient();

                    }
                }
            }
            return client;
        }
        public void setHeader(string key,string val) 
        {
            client.DefaultRequestHeaders.Add(key, val);
        }
        public async Task<string> PostAsync(string url, Dictionary<string, string> body)//post异步请求方法
        {


            var content = new MultipartFormDataContent();
            foreach (var k in body)
            {
                content.Add(new StringContent(k.Value), k.Key);
            }
            try
            {

                //由HttpClient发出异步Post请求
                HttpResponseMessage res = await client.PostAsync(url, content);
                if (res.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    string str = res.Content.ReadAsStringAsync().Result;
                    return str;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                string res = this.errorReport(ex);
                return this.errorReport(ex);
            }
        }

        public string Post(string url, Dictionary<string, string> body)//post同步请求方法
        {
            try
            {
                var content = new MultipartFormDataContent();
                foreach (var k in body)
                {
                    content.Add(new StringContent(k.Value), k.Key);
                }
                Task<HttpResponseMessage> res = client.PostAsync(url, content);
                if (res.Result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    string str = res.Result.Content.ReadAsStringAsync().Result;
                    return str;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                string res = this.errorReport(ex);
                return this.errorReport(ex);
            }
        }

        public string Get(string url)
        {
            try
            {
                var responseString = client.GetStringAsync(url);
                return responseString.Result;
            }
            catch (Exception ex)
            {
                string res = this.errorReport(ex);
                return this.errorReport(ex);
            }
        }

        protected string  errorReport(Exception e)
        {
            string str = "something wrong";
            System.IO.File.WriteAllText((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000 + "error.txt", e.Message);
            return str;
        }


    }
}
